import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
    state: () => ({
        user: null,
        token: null,
        refreshToken: null, // 刷新令牌
        isAuthenticated: false,
        balance: 1000, // 初始模拟余额
        balanceLogs: [
        ],
    }),

    actions: {
        login(userData, token, refreshToken) {
            this.user = userData;
            this.token = token;
            this.refreshToken = refreshToken; // 保存刷新令牌
            this.isAuthenticated = true;

            // 保存到localStorage
            localStorage.setItem('user', JSON.stringify(userData));
            localStorage.setItem('token', token);
            localStorage.setItem('refreshToken', refreshToken);
        },

        setToken(newToken) {
            this.token = newToken;
            localStorage.setItem('token', newToken);
        },

        logout() {
            this.user = null;
            this.token = null;
            this.refreshToken = null;
            this.isAuthenticated = false;
            localStorage.removeItem('user');
            localStorage.removeItem('token');
            localStorage.removeItem('refreshToken');
        },

        initialize() {
            const user = localStorage.getItem('user');
            const token = localStorage.getItem('token');
            const refreshToken = localStorage.getItem('refreshToken');

            if (user && token && refreshToken) {
                this.user = JSON.parse(user);
                this.token = token;
                this.refreshToken = refreshToken;
                this.isAuthenticated = true;
            }
        },

        deductBalance(amount, remark = '消费') {
            if (this.balance >= amount) {
                this.balance -= amount;
                this.balanceLogs.unshift({
                    type: '消费',
                    amount: -amount,
                    remark,
                    time: new Date().toLocaleString()
                });
                return true;
            }
            return false;
        },

        recharge(amount, remark = '充值') {
            this.balance += amount;
            this.balanceLogs.unshift({
                type: '充值',
                amount: +amount,
                remark,
                time: new Date().toLocaleString()
            });
        },

        deleteLog(index) {
            this.balanceLogs.splice(index, 1)
        }
    },

    getters: {
        isBuyer: (state) => state.user?.role === 'BUYER',
        isSeller: (state) => state.user?.role === 'SELLER',
        isAdmin: (state) => state.user?.role === 'ADMIN',
        userName: (state) => state.user?.username || '用户'
    }
});